package com.osfw.framework.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.antherd.smcrypto.sm2.Keypair;
import com.antherd.smcrypto.sm2.Sm2;
import com.osfw.framework.config.Global;
import com.osfw.framework.constants.Constants;
import com.osfw.framework.core.domain.RestfulResult;
import com.osfw.framework.exception.UserException;
import com.osfw.framework.utils.CookieUtils;
import com.osfw.framework.utils.StringUtils;
import com.osfw.framework.utils.http.RequestUtil;
import com.osfw.framework.web.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 登录验证  DB Adminer
 */
@Controller
@RequestMapping()
public class LoginController {
    private String prefix = "osfw";

    @Autowired
    private LoginService loginService;

    @GetMapping(value = {"", "/osfw"})
    public Object login(HttpServletRequest request) {
        return new RedirectView(RequestUtil.getBasePath(request) + Global.getIndexUrl());
    }

    @GetMapping("/osfw/login")
    public String login(ModelMap mmap, HttpServletRequest request) {
        Keypair keypair = Sm2.generateKeyPairHex();
        mmap.put("publicKey", keypair.getPublicKey());
        mmap.put("captchaEnabled", Global.isCaptchaEnabled());
        StpUtil.getTokenSessionByToken(CookieUtils.getCookie(request, Constants.TEMP_TOKEN_NAME)).set("privateKey", keypair.getPrivateKey());
        return prefix + "/login";
    }

    @PostMapping("/osfw/doLogin")
    @ResponseBody
    public RestfulResult doLogin(@Valid @RequestParam String phonenumber, @Valid @RequestParam String password, @Valid @RequestParam String kaptcha, HttpServletRequest request) {
        try {
            String privateKey = StpUtil.getTokenSessionByToken(CookieUtils.getCookie(request, Constants.TEMP_TOKEN_NAME)).get("privateKey").toString();
            if(Global.isCaptchaEnabled()) {
                kaptcha = Sm2.doDecrypt(kaptcha, privateKey);
                String code = StpUtil.getTokenSessionByToken(CookieUtils.getCookie(request, com.osfw.framework.constants.Constants.TEMP_TOKEN_NAME)).getString(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
                if (StringUtils.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
                    return RestfulResult.error("验证码错误");
                }
                // 验证码清除，防止多次使用。
                StpUtil.getTokenSessionByToken(CookieUtils.getCookie(request, com.osfw.framework.constants.Constants.TEMP_TOKEN_NAME)).delete(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
            }
            phonenumber = Sm2.doDecrypt(phonenumber, privateKey);
            password = Sm2.doDecrypt(password, privateKey);
        }catch (Exception e) {
            UserException.throwUserPasswordNotMatchException();
        }
        loginService.login(phonenumber, password);
        return RestfulResult.success("认证通过");
    }

    @SaIgnore
    @GetMapping("/osfw/logout")
    public String logout() {
        loginService.logout(StpUtil.getLoginId());
        return "redirect:" + Global.getLoginUrl();
    }



}
